﻿using Microsoft.Win32;
using Prism.Commands;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Model.DbContext.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System.IO;
using System.Windows;
using System.Windows.Input;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class TemplateSettingNewViewModel : DialogViewModelBase, IDialogAware
    {
        private int _templateType = 0;
        private DelegateCommand<object> _okDialogCommand;
        private DelegateCommand _uploadFilesCommand;
        //private IAchievementService _specOutputService;
        //private IImportUtilityService _importUtilityService;
        private ITemplateSettingService _templateSettingService;
        public TemplateSettingNewViewModel(ITemplateSettingService templateSettingService, IDialogService dialogService) : base(dialogService)
        {
            Title = "新建模板";
            //_specOutputService = specOutputService;
            //_importUtilityService = importUtilityService;
            _templateSettingService = templateSettingService;
        }

        public override void OnDialogOpened(IDialogParameters parameters)
        {

            //ComboxList.Add(new ComboBoxItemModel<SimpleIntModel> { Description = "内置的", IsEnable = true, SelectedModel = new SimpleIntModel { v1 = -1 } });
            ComboxList.Add(new ComboBoxItemModel<SimpleIntModel> { Description = "规格书", IsEnable = true, SelectedModel = new SimpleIntModel { v1 = (int)TemplateType.SPEC } });
            ComboxList.Add(new ComboBoxItemModel<SimpleIntModel> { Description = "索引表", IsEnable = true, SelectedModel = new SimpleIntModel { v1 = (int)TemplateType.INDEX } });
            ComboxList.Add(new ComboBoxItemModel<SimpleIntModel> { Description = "材料表", IsEnable = true, SelectedModel = new SimpleIntModel { v1 = (int)TemplateType.BOM } });
            ComboxList.Add(new ComboBoxItemModel<SimpleIntModel> { Description = "安装图", IsEnable = true, SelectedModel = new SimpleIntModel { v1 = (int)TemplateType.HOOKUP } });
            ComboxList.Add(new ComboBoxItemModel<SimpleIntModel> { Description = "接线相关", IsEnable = true, SelectedModel = new SimpleIntModel { v1 = (int)TemplateType.WIRING } });
            //this.SelectedModel = ComboxList[0].SelectedModel;

            IOTypeList.Add(new SimpleIntModel { v1 = 0, v2 = "输入用" });
            IOTypeList.Add(new SimpleIntModel { v1 = 1, v2 = "输出用" });
            //this.SelectedIOType = IOTypeList[0].SelectedModel;

            base.OnDialogOpened(parameters);
        }

        public List<ComboBoxItemModel<SimpleIntModel>> ComboxList { get; set; } = new List<ComboBoxItemModel<SimpleIntModel>>();
        private Visibility _NeedInOut;

        public Visibility NeedInOut
        {
            get { return _NeedInOut; }
            set
            {
                SetProperty(ref _NeedInOut, value);
            }
        }

        private SimpleIntModel _selectedModel;
        public SimpleIntModel SelectedModel
        {
            get { return _selectedModel; }
            set
            {

                SetProperty(ref _selectedModel, value);

                if (_selectedModel.v1 == (int)TemplateType.SPEC)
                {
                    //规格书
                    NeedInOut = Visibility.Collapsed;
                    SelectedIOType = null;
                }
                else
                {
                    NeedInOut = Visibility.Visible;
                }
            }
        }
        public List<SimpleIntModel> IOTypeList { get; set; } = new List<SimpleIntModel>();

        private SimpleIntModel _selectedIOType;
        public SimpleIntModel SelectedIOType
        {
            get { return _selectedIOType; }
            set { SetProperty(ref _selectedIOType, value); }
        }

        private string _templateName = "";
        public string TemplateName
        {
            get { return _templateName; }
            set { SetProperty(ref _templateName, value); }
        }

        private string _generateFunc = "";
        public string GenerateFunc
        {
            get { return _generateFunc; }
            set { SetProperty(ref _generateFunc, value); }
        }

        private string _templatePath = "";
        public string TemplatePath
        {
            get { return _templatePath; }
            set { SetProperty(ref _templatePath, value); }
        }
        private string _parameters = "";
        public string Parameters
        {
            get { return _parameters; }
            set { SetProperty(ref _parameters, value); }
        }
        private string _description = "";
        public string Description
        {
            get { return _description; }
            set { SetProperty(ref _description, value); }
        }
        private string _sql = "";
        public string SQL
        {
            get { return _sql; }
            set { SetProperty(ref _sql, value); }
        }
        private string _files = "";
        public string Files
        {
            get { return _files; }
            set { SetProperty(ref _files, value); }
        }
        /// <summary>
        /// 新增 report
        /// </summary>
        public ICommand OkDialogCommand
        {
            get
            {
                if (_okDialogCommand != null) return _okDialogCommand;
                _okDialogCommand = new DelegateCommand<object>(onOkDialogCommand);
                return _okDialogCommand;
            }
        }
        public ICommand UploadFilesCommand
        {
            get
            {
                if (_uploadFilesCommand != null) return _uploadFilesCommand;
                _uploadFilesCommand = new DelegateCommand(onUploadFilesCommand);
                return _uploadFilesCommand;
            }
        }
        private async void onOkDialogCommand(object parameter)
        {
            string proId = GlobalObject.CurrentProject.ProjId.ToString();

            if (_selectedModel == null)
            {
                Dialog.ShowAltert("您的选择不规范，请选择新建模板类型。");
                return;
            }
            if (_selectedIOType == null && _selectedModel.v1 != (int)TemplateType.SPEC)
            {
                Dialog.ShowAltert("您的选择不规范，请选择新建输入/输出。");
                return;
            }
            if (_templateName.IsNullOrEmpty())
            {
                Dialog.ShowAltert("您的输入不规范，模板名称不能为空。");
                return;
            }
            _templatePath = GlobalObject.CurrentProject.ProjName;
            //if (_templatePath.IsNullOrEmpty())
            //{
            //    Dialog.ShowAltert("您的输入不规范，模板路径不能为空。");
            //    return;
            //}
            if (Files == "")
            {
                var result = MessageBox.Show($"您未上传一个对应的模板文件，是否要新建一个空白的模板，您也可以稍后再上传模板文件。\n单击'确定'以继续，单击'取消'后，点击“选取模板文件”来上传", "确认",
                    MessageBoxButton.OKCancel, MessageBoxImage.Information);
                if (result == MessageBoxResult.Cancel)
                {
                    return;
                }
            }
            try
            {
                Report report = new Report
                {
                    Description = _description,
                    GenerateFunc = GenerateFunc,
                    Name = _templateName,
                    SQL = _sql,
                    TemplatePath = _templatePath,
                    Type = (TemplateType)_selectedModel.v1,
                    Parameters = _parameters,
                    InOrOut = _selectedIOType == null ? -1 : _selectedIOType.v1
                };
                var r = await _templateSettingService.CreateTemplateAsync(proId, report);

                if (r.succeeded == true)
                {
                    foreach (var item in Files.Split("\n"))
                    {
                        string filePath = item;
                        if (File.Exists(filePath))
                        {
                            if (filePath.Contains(".xls") && !filePath.Contains(".xlsx"))
                            {
                                filePath = ExcelHelper.xls2xlsx(filePath.Replace(Path.GetFileName(filePath), ""), Path.GetFileName(filePath));
                            }
                            using var fileStream = new FileStream(filePath, FileMode.Open);
                            string fileNameExtension = Path.GetExtension(filePath);
                            await _templateSettingService.UploadTemplateFileAsync(proId, report.Type, fileStream, report.Name + fileNameExtension, report.InOrOut);
                        }
                    }
                    Dialog.ShowAltert("新建成功！！！");
                    RaiseRequestClose(new DialogResult(ButtonResult.OK));
                }
                else
                {
                    Dialog.ShowAltert(r.errors); 
                }
            }
            catch (Exception x)
            {
                var xMessage = $"新建失败：{x.Message}！！！";
                LoggerHelper.Current.Error(xMessage, x);
                Dialog.ShowAltert(xMessage);
            }
        }

        private void onUploadFilesCommand()
        {
            string fileFilter = "模板文件(优先xlsx)|*.xls;*.xlsx;*.xml";
            var openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = true;
            openFileDialog.Filter = fileFilter;
            if (openFileDialog.ShowDialog() == true)
            {
                Files = "";
                bool isMessage = false;
                foreach (string filename in openFileDialog.FileNames)
                {
                    if (filename.Contains(".xls") && !filename.Contains(".xlsx") && !isMessage)
                    {
                        System.Windows.Forms.MessageBox.Show("请优先选择xlsx格式的文件，若选xls，DI-Intools将帮您转为xlsx，但是某些内容会失真，请悉知！", "提示", System.Windows.Forms.MessageBoxButtons.OK);
                        isMessage = true;
                    }
                    Files += filename + "\n";
                }
            }
        }
    }
}
